<template>
  <div>
	<div id="uploader">
		<div id="picker">选择文件</div>
		<ul id="theList">
			<li class="video_info_title">
				<span class="file_name">文件</span>
				<span class="US">上传/暂停</span>
				<span class="DC">删除/清除</span>
			</li>
		</ul>
	</div>
	<span class="video_all" @click="goVideoList">视频主页</span>
	<span class="lookUploadFile" @click="goUserCore">查看上传的文件</span>
  </div>
</template>

<script>
import video_url from './url'
import file_path from './file_url'

export default {
	name: "Upload",
	data(){
		return{
			userInfo:{userId:"admin", md5:""},
			chunkSize : 5*1024*1024,	// 分片大小
			uniqueFileName:null,	// 被上传文件的名称
			md5Mark:null,	// 文件的md5
			chunksMd5Array: [[],[],[],[],[]],// 分片的md5
			chunkCount: [0,0,0,0,0],	// 分片的数量
			timers: [{},{},{},{},{}],	// 定时器
			now_file_id:null,	// 当前正在上传的id
			now_file_index: -1,	// 当前正在上传的下标
			is_video:false,
			vid:null,
			vpath:null,
			suffix:null,	// 获取后缀
			backEndUrl: video_url[0].url,	// 上传分片的路径
			clearChunksUrl: video_url[1].url,	// 删除分片时的路径
			downloadUrl: video_url[2].url,	// 文件下载的路径
			progressUrl: video_url[3].url,	// 获取下载进度的路径
			uploader: null,
			file_array: [],	// 上传队列,
			file_md5_array: [],	// 获取分片件MD5的队列
			isBusily: false,	// 当前是否有文件上传
			fileListMaxSize: 5,	// 上传文件队列中的最大值
			index: -1,	// 处理md5标签的下标,
			flag: true,	// 标记
		}
	},
	methods:{
		addVideo(){
			// API
			this.uploader = WebUploader.create({
				swf: "/static/js/Uploader.swf"
				, server: this.backEndUrl
				, pick: "#picker"
				, resize: false
				, dnd: "#theList"
				, paste: document.body
				, disableGlobalDnd: true
				, compress: false
				, prepareNextFile: true
				, chunked: true
				, chunkSize: this.chunkSize
				, threads: 3	// 这个参数官方API是boolean，我有点迷
				, formData: () => {return $.extend(true, {}, this.userInfo);}
				, fileNumLimit: this.fileListMaxSize
				, fileSingleSizeLimit: 2000 * 1024 * 1024
				, duplicate: true
				, accept:{
					title:'文件上传',
					extensions:'*'
				}
			});

			this.uploader.on("fileQueued", (file) => {

				$("#theList").append('<li id="'+file.id+'" class="video_info">' +
					'<img /><span class="file_name">'+file.name+
					'</span><span class="itemDel">删除</span><span class="itemClear">清除</span><span class="itemUpload">上传</span><span class="itemCancel">取消</span><span class="itemStop">暂停</span>' +
					'<div class="percentage"></div><span class="text_info"></span>' +
					'</li>');
					
				this.file_md5_array.push(file);
				this.flag = true;
				/*
					选择多个文件时，会出现问题(貌似解决)
				*/
				console.log(Number(file.id.split("_")[2])%this.fileListMaxSize);
				this.timers[Number(file.id.split("_")[2])%this.fileListMaxSize] = setInterval(() => {
					console.log(this.file_md5_array.length);
					if(this.flag){
						let nowfile = this.file_md5_array[0];
						let index = Number(nowfile.id.split("_")[2])%this.fileListMaxSize;
						console.log(index);
						let chunkCount = Math.ceil(nowfile.size / this.chunkSize);
						this.chunksMd5Array[index]=[];
						$("#" + nowfile.id + " .text_info").text("正在计算，请稍后");
						for (let i = 1; i <= chunkCount; i++) {
							if(i == 1) this.flag = false;
							(new WebUploader.Uploader()).md5File(this.file_md5_array[0],Number((i-1)*this.chunkSize),Number((i-1)*this.chunkSize)+Number(1024*1024*1)).progress(function(percentage){
							}).then(val => {
								this.chunksMd5Array[index].push(val);
								if(i==chunkCount){
									$("#"+nowfile.id+" .itemUpload").show();
									$("#"+nowfile.id+" .itemDel").show();
									$("#" + nowfile.id + " .text_info").text("计算完毕");
									console.log(this.chunksMd5Array);
									this.file_md5_array.splice(0,1);
									clearInterval(this.timers[index]);
									if(this.file_md5_array.length == 0) {
										this.flag = false;
									}else this.flag = true;
									
								}
							});
						}
					}
				},500);
			});

			$("#theList").on("click", ".itemUpload", () => {

				let file_id = event.target.parentElement.getAttribute("id");

				this.file_array.push(file_id);

				$("#"+file_id+" .text_info").text("正在排队");

				// this.uploader.upload(file_id);
				$("#"+file_id+" .itemUpload").hide();
				$("#"+file_id+" .itemCancel").show();
			});

			$("#theList").on("click", ".itemCancel", () => {

			let file_id = event.target.parentElement.getAttribute("id");

			let i = 0;

			this.file_array.filter(item => {
				if(item == file_id){
					this.file_array.splice(i,1);
					return ;
				}
				i++;
			})

			this.uploader.removeFile(file_id);	//从上传队列移出

			$("#"+file_id+" .text_info").text("");
			$("#"+file_id+" .itemCancel").hide();
			$("#"+file_id+" .itemUpload").show();

			});

			$("#theList").on("click", ".itemStop", () => {

				let file_id = event.target.parentElement.getAttribute("id");

				this.uploader.stop(true);
				$("#"+file_id+" .itemStop").hide();
				$("#"+file_id+" .itemUpload").show();
				this.uploader.removeFile(file_id);	//从上传队列移出
				this.file_array.splice(0,1);
				this.isBusily = false;
			});

			//todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件
			$("#theList").on("click", ".itemDel", () => {
				let file_id = event.target.parentElement.getAttribute("id");
				// console.log(this.now_file_id+"_____"+file_id);
				if(this.now_file_id == file_id) this.uploader.stop(true);    // 暂定上传操作
				// console.log("zhanghao");
				setTimeout(() => {
					$.ajax({    // 发送请求到后台，然后删除分片和temp文件
						type: 'POST',
						url: this.clearChunksUrl,
						data: {
							name: this.uniqueFileName
							, chunks: -1
							, ext: this.suffix
							, md5: this.md5Mark
						}
					})
					this.uploader.removeFile(file_id,true);	//从上传文件列表中删除
					$("#"+file_id).remove();	//从上传列表dom中删除
					this.isBusily = false;
					this.file_array.splice(0,1);
				},10);

			});

			$("#theList").on("click",".itemClear",() => {
				console.log(".itemClear");
				let file_id = event.target.parentElement.getAttribute("id");
				this.uploader.removeFile(file_id,true);	//从上传文件列表中删除
				$("#"+file_id).remove();	//从上传列表dom中删除
			})

			this.uploader.on("uploadProgress", (file, percentage) => {

				var text = $("#" + file.id + " .percentage").text();
				if(text != '正在检索...'){
					const now_percentage = Math.round(percentage*10000)/100;
					$("#"+file.id+" .percentage").css({"width":now_percentage + "%"});
				}
				if(percentage >= 1){
					$("#"+file.id+" .itemDel").hide();
					$("#"+file.id+" .itemStop").hide();
					$("#"+file.id+" .itemUpload").hide();
					$("#"+file.id+" .itemCancel").hide();
					$("#" + file.id + " .text_info").text("正在处理");
					this.is_video = true;
				}
			});


		},
		UploadComlate(file){
			$("#" + file.id + " .text_info").text("上传完毕");
			$("#"+file.id+" .itemClear").show();

			this.file_array.splice(0,1);
			this.isBusily = false;

			// this.uploader.removeFile(file.id,true);
		},
		goVideoList(){
			const { href } = this.$router.resolve({
				path: '/videoIndex'
			});
			window.open(href, '_blank');
		},
		goUserCore(){
			const { href } = this.$router.resolve({
				path:"/userCore",
                query:{
                    videoUser: 1
				}
			});
			window.open(href, '_blank');
			
		},
	},
	watch:{
		file_array(){
			console.log(this.file_array);
			if(!this.isBusily&&this.file_array.length > 0){
				this.isBusily = true;
				let file_id = this.file_array[0];
				this.uploader.upload(file_id);
				$("#"+file_id+" .text_info").text("正在上传");
				this.now_file_id = file_id;
				// console.log(file_id.split("_"));
				this.now_file_index = Number(file_id.split("_")[2])%this.fileListMaxSize;
				$("#"+file_id+" .itemCancel").hide();
				$("#"+file_id+" .itemStop").show();
			}
		}
	},
	created(){
		WebUploader.Uploader.register({
			"before-send-file": "beforeSendFile"
			, "before-send": "beforeSend"
			, "after-send-file": "afterSendFile"
		}, {
			beforeSendFile: (file) => {
				//秒传验证
				var task = new $.Deferred();
				(new WebUploader.Uploader()).md5File(file, 0, 10*1024*1024).progress((percentage) => {
					// console.log("percentage——"+percentage);
				}).then((val) => {
					// console.log(this.userInfo);
					// console.log(this.backEndUrl);
					this.md5Mark = val;
					this.userInfo.md5 = val;

					$.ajax({
						type: "POST"
						, url: this.backEndUrl
						, data: {
							status: "md5Check"
							, md5: val
							, vid: this.vid
							, vpath: this.vpath
							, suffix: this.suffix
						}
						, cache: false
						, timeout: 1000 //todo 超时的话，只能认为该文件不曾上传过
						, dataType: "json"
					}).then((data, textStatus, jqXHR) => {

						if(data.ifExist){   //若存在，这返回失败给WebUploader，表明该文件不需要上传
							task.reject();
							$(".percentage").css({"width":"100%"});
							$("#" + file.id + " .text_info").text("上传完毕");
							$(".itemDel").hide();
							$(".itemStop").hide();
							$(".itemUpload").hide();
							$(".itemClear").show();
							uploader.skipFile(file);
							file.path = data.path;
							this.UploadComlate(file);
						}else{
							task.resolve();
							//拿到上传文件的唯一名称，用于断点续传
							this.uniqueFileName = md5(''+this.userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size);
						}
					}, (jqXHR, textStatus, errorThrown) => {    //任何形式的验证失败，都触发重新上传
						task.resolve();
						//拿到上传文件的唯一名称，用于断点续传
						this.uniqueFileName = md5(''+this.userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size);
					});
				});
				return $.when(task);
			},
			beforeSend: (block) => {
				//分片验证是否已传过，用于断点续传
				var task = new $.Deferred();
				$.ajax({
					type: "POST"
					, url: this.backEndUrl
					, data: {
						status: "chunkCheck"
						, name: this.uniqueFileName
						, chunkIndex: block.chunk
						, size: block.end - block.start
						, md5: this.chunksMd5Array[this.now_file_index][block.chunk]
					}
					, cache: false
					, timeout: 1000 //todo 超时的话，只能认为该分片未上传过
					, dataType: "json"
				}).then((data, textStatus, jqXHR) => {
					if(data.ifExist){   //若存在，返回失败给WebUploader，表明该分块不需要上传
						$("#"+this.now_file_id+" .text_info").text("正在检索...");
						task.reject()
					}else{
						var text = $("#"+this.now_file_id+" .text_info").text();
						if(text == "正在检索..."){
							$("#"+this.now_file_id+" .text_info").text("");
						}
						$(".default_box").css({"display":"block"});
                    	this.userInfo.md5 = this.chunksMd5Array[this.now_file_index][block.chunk];
						task.resolve();
					}
				}, (jqXHR, textStatus, errorThrown) => {    //任何形式的验证失败，都触发重新上传
					this.userInfo.md5 = this.chunksMd5Array[this.now_file_index][block.chunk];
					task.resolve();
				});

				return $.when(task);
			},
			afterSendFile: (file) => {
				var chunksTotal = 0;
				if((chunksTotal = Math.ceil(file.size/this.chunkSize)) > 1){
					//合并请求
					var task = new $.Deferred();
					$.ajax({
						type: "POST"
						, url: this.backEndUrl
						, data: {
							status: "chunksMerge"
							, name: this.uniqueFileName
							, chunks: chunksTotal
							, ext: file.ext
							, md5: this.md5Mark
						}
						, cache: false
						, dataType: "json"
					}).then((data, textStatus, jqXHR) => {
						//todo 检查响应是否正常
						task.resolve();
						file.path = data.path;
						this.UploadComlate(file);

					}, (jqXHR, textStatus, errorThrown) => {
						task.reject();
					});

					return $.when(task);
				}else{
					this.UploadComlate(file);
				}
			}
		});
	},
	mounted(){
		this.addVideo();
		// console.log(this.uploader);
	}
}


</script>

<style scope>
	*{
		text-decoration: none;
		list-style: none;
	}
	#theList{
		position: relative;
		width: 80%;
		min-height: 600px;
		margin-left: 10%;
		border: 1px solid #ddd;
	}
	.video_info,.video_info_title{
		position: relative;
		display: inline-block;
		/* float: left; */
		width: 103.5%;
		height: 80px;
		margin-left: -3.5%;
		border-bottom: 1px solid #ddd;
		color: #000;
		font-size: 14px;
		font-weight: bold;
		letter-spacing: 1px;
		line-height: 80px;
		/* background-color: red; */
	}
	.video_info_title{
		background-color: #eee;
	}
	.percentage{
		position: absolute;
		top: 0px;
		left: 0px;
		width: 0%;
		height: 100%;
		background-color: #aaffff;
		z-index: -1;
	}
	#theList .itemStop,#theList .itemClear, #theList .itemCancel, #theList .itemUpload, #theList .itemDel{
		display: none;
	}
	.itemDel,.itemClear,.itemStop,.itemUpload,.itemCancel,.US,.DC{
		display: inline-block;
		width: 80px;
		font-weight: bold;
		letter-spacing: 2px;
		text-align: center;
	}
	.itemDel,.itemClear,.itemStop,.itemUpload,.itemCancel{
		height: 40px;
		top: 20px;
		line-height: 40px;
		border-radius: 5px;
		color: #eee;
		cursor: pointer;
		font-size: 14px;
	}
	.itemUpload{
		background-color: #007aff;
	}
	.itemStop{
		background-color: #ff5500;
	}
	.itemClear{
		background-color: #8a6de9;
	}
	.itemDel{
		background-color: #dd524d;
	}
  .itemCancel{
    background-color: #f0ad4e;
  }
	.itemUpload, .itemStop, .itemCancel, .US{
		position: absolute;
		right: 120px;
	}
	.itemDel, .itemClear, .DC{
		position: absolute;
		right: 10px;
	}
	.text_info{
		position: absolute;
		right: 240px;
	}
	.file_name{
		float: left;
		margin-left: 8px;
		width: 85%;

		overflow:hidden;
		word-break:keep-all;
		white-space:nowrap;
		text-overflow:ellipsis;
	}
	.video_all,.lookUploadFile{
		width: 100px;
		height: 40px;
		text-decoration: none;
		display: inline-block;
		border-radius: 3px;
		user-select: none;
		background: #4AB2FE;
		cursor: pointer;
		text-align: center;
		color: #fff;
		font-size: 15px;
		font-weight: bold;
		line-height: 40px;
		letter-spacing: 3px;
	}
	.lookUploadFile{
		width: 180px;
	}
	.video_all a,.lookUploadFile a{
		
	}
	
</style>
